<template>
  <div class="dataBase">
    <ContentWrap>
      <el-form label-width="100px" ref="searchRef" :model="queryParams">
        <el-row>
          <el-col :span="6">
            <el-form-item label="系统名称" prop="name">
              <ns-input v-model="queryParams.name" clearable placeholder="请输入系统名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="系统状态" prop="status">
              <el-select
                v-model="queryParams.status"
                placeholder="请选择系统状态"
                clearable
                class="!w-240px"
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="授权状态" prop="ruleStatus">
              <el-select
                v-model="queryParams.ruleStatus"
                placeholder="请选择授权状态"
                clearable
                class="!w-240px"
              >
                <el-option label="已授权" :value="1" />
                <el-option label="未授权" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" class="text-right">
            <el-button @click="searchReset" plain>重置</el-button>
            <el-button @click="search" plain>搜索</el-button>
          </el-col>
        </el-row>
      </el-form>
    </ContentWrap>
    <ContentWrap>
      <el-form-item>
        <el-button type="primary" @click="handleAuthorization(1, 1)"> 授权上线权限</el-button>
        <el-button type="primary" @click="handleAuthorization(1, 2)"> 授权下线权限</el-button>
        <el-button plain @click="handleAuthorization(0, 1)"> 回收上线权限</el-button>
        <el-button plain @click="handleAuthorization(0, 2)"> 回收下线权限</el-button>
      </el-form-item>
      <el-table
        v-loading="loading"
        :data="list"
        :default-expand-all="isExpandAll"
        row-key="id"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" />
        <el-table-column :show-overflow-tooltip="true" label="系统名称" prop="name" width="250" />
        <el-table-column label="上线权限状态" prop="ruleStatusName">
          <template #default="{ row }">
            <div>
              <div v-if="row.ruleStatus == 1">
                <div v-if="row.radius == 2">本系统及下级系统</div>
                <div v-else>本系统</div>
              </div>
              <div v-else>未授权</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="下线权限状态" prop="ruleStatusName2">
          <template #default="{ row }">
            <div>
              <div v-if="row.ruleStatus2 == 1">
                <div v-if="row.radius2 == 2">本系统及下级系统</div>
                <div v-else>本系统</div>
              </div>
              <div v-else>未授权</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
          </template>
        </el-table-column>
      </el-table>
    </ContentWrap>
  </div>
</template>

<script setup lang="tsx">
import { Check, Close } from '@element-plus/icons-vue'
import * as api from '@/api/dataAuthorization'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const route = useRoute()
const searchRef = ref()
const isExpandAll = ref(true)
const loading = ref(true) // 列表的加载中
const list = ref<any>([]) // 列表的数据
const queryParams = ref({
  name: '',
  status: '',
  ruleStatus: ''
})

const searchReset = () => {
  searchRef.value.resetFields()
  search()
}

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
  console.log('multipleSelection.value', multipleSelection.value)
}

const search = () => {
  getList()
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const { data } = await api.sysTree({
      ...queryParams.value,
      userId: route.query.id,
      dateStatus: 1
    })
    list.value = data
  } finally {
    loading.value = false
  }
}

const radius = ref('1')

const selectOptions = () => [
  h(ElOption, { label: '本系统', value: '1' }),
  h(ElOption, { label: '本系统以及下级系统', value: '2' })
]

const select = () =>
  h('div', [
    h('span', '授权范围：'),
    h(
      ElSelect,
      {
        modelValue: radius.value,
        placeholder: '请选择',
        'onUpdate:modelValue': (val) => {
          radius.value = val
        },
        style: 'width:300px'
      },
      selectOptions
    )
  ])

//available: 0-回收权限 1-授权
// type：1-上线 2-下线
const handleAuthorization = async (available, type) => {
  if (multipleSelection.value.length == 0) {
    message.warning('请选择授权系统')
    return
  }
  var params
  if (available === 1) {
    ElMessageBox({
      title: '权限授权',
      message: select,
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    }).then(async () => {
      params = multipleSelection.value?.map((item: any) => {
        return {
          userId: route.query.id,
          relevancyId: item.id,
          relevancyType: '2',
          available: type == 1 ? available : item.ruleStatus,
          available2: type == 2 ? available : item.ruleStatus2,
          radius: type == 1 ? radius.value : item.radius,
          radius2: type == 2 ? radius.value : item.radius2
        }
      })
      const data = await api.dataAuthorizationUpdate(params)
      console.log('data', data)
      if (data) {
        getList()
        message.success('操作成功')
      }
    })
  } else {
    params = multipleSelection.value?.map((item: any) => {
      return {
        userId: route.query.id,
        relevancyId: item.id,
        relevancyType: '2',
        available: type == 1 ? available : item.ruleStatus,
        available2: type == 2 ? available : item.ruleStatus2,
        radius: item.radius,
        radius2: item.radius2
      }
    })
    const data = await api.dataAuthorizationUpdate(params)
    if (data) {
      getList()
      message.success('操作成功')
    }
  }
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss">
.dataBase {
  .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: inline-flex;
    align-items: center;
    line-height: 23px;
    padding-left: 12px;
  }
  .el-form .el-select {
    width: 100%;
  }
  :deep(.hide-expand .cell) {
    display: none;
  }
  :deep(.el-form .el-cascader) {
    width: 100%;
  }
  :deep(.operate-btn .el-button.is-text) {
    padding: 0 10px 0 0;
  }
  .el-dropdown-link:focus {
    outline: none;
  }
}
</style>
